package pl.edu.agh.io.sylvia.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import pl.edu.agh.io.sylvia.entity.Server;



public class ServerDAO extends GenericDAO {

	@Override
	public List<Server> getAll() {
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		List<Server> results= new ArrayList<Server>();
		
		try {
			statement = connection.prepareStatement("SELECT * FROM SERVERS");
			resultSet = statement.executeQuery();
			
			while(resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				String host = resultSet.getString("host");
				String login = resultSet.getString("login");
				String password = resultSet.getString("password");
				short port = resultSet.getShort("port");
				results.add(new Server(id, name, host, login, password, port));
			}
			return results;
		} catch (SQLException e) {
			log.log(Level.SEVERE, e.getMessage(), e);
			return null;
		} finally {
			if (resultSet != null) try {
				resultSet.close();
			} catch(SQLException e) {};
			if (statement != null) try {
				statement.close();
			} catch (SQLException e) {};
		}
	}

	@Override
	public Server getById(int id) {
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		
		try {
			statement = connection.prepareStatement("SELECT * FROM SERVERS WHERE id = ?");
			statement.setInt(1, id);
			resultSet = statement.executeQuery();
			
			if (resultSet.next()) {
				String name = resultSet.getString("name");
				String host = resultSet.getString("host");
				String login = resultSet.getString("login");
				String password = resultSet.getString("password");
				short port = resultSet.getShort("port");
				return new Server(id, name, host, login, password, port);
			} else {
				return null;
			}
		} catch (SQLException e) {
			log.log(Level.SEVERE, e.getMessage(), e);
			e.printStackTrace();
			return null;
		} finally {
			if (resultSet != null) try {
				resultSet.close();
			} catch(SQLException e) {};
			if (statement != null) try {
				statement.close();
			} catch (SQLException e) {};
		}
	}

}
